package com.wn.cloud.provider.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.wn.cloud.common.constant.ResponseEnum;
import com.wn.cloud.common.response.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @FileName: PayMentController
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/3/7 - 23:38
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
@Slf4j
@RestController
@RequestMapping("/payment/hystrix")
public class PaymentController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/{id}")
    public DataResult<String> getOne(@PathVariable("id") long id) {
        if (id < 0) {
            int n = 10 / 0;
        }
        String str = "端口: " + serverPort + "    线程: " + Thread.currentThread().getName() + "    id: " + id;
        return DataResult.genDataResult(ResponseEnum.SUCCESS, str);
    }

    @GetMapping("/timeout")
    @HystrixCommand(fallbackMethod = "getTimeoutFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public DataResult<String> getTimeout() {
        int time = 3000;
        try {
            TimeUnit.MILLISECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String str = "端口: " + serverPort + "    线程: " + Thread.currentThread().getName() + "    耗时(秒): " + time;
        return DataResult.genDataResult(ResponseEnum.SUCCESS, str);
    }

    public DataResult<String> getTimeoutFallback() {
        return DataResult.genDataResult(ResponseEnum.SUCCESS, "服务端系统异常");
    }
}
